package cmpe226.spring2011.project1;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Take DifferenceDTO and "flatten" so that dates are in columns and symbol+values are in rows
 * use PrinterWriter to write a csv file
 */
public class DataExporter {
    private Properties config = new Properties();
	
    public static void main(String[] args) {
        DataExporter app = new DataExporter();
        app.loadProperties();
        
        long starttime = System.currentTimeMillis();
        app.exportData(args[0], args[1], args[2], args[3]);
        long elapsed = System.currentTimeMillis() - starttime;
        
        System.out.println("Elapsed Time: " + (elapsed/1000F) + " seconds");
    }
    
    private void loadProperties() {
        InputStream in = ImportStocksApp.class.getClassLoader().getResourceAsStream("setup.properties");
        try {
            config.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void exportData(String startDate, String endDate, String symbolList, String filename) {
        String dbname = "localhost/" + config.getProperty("dbname");
        String user = config.getProperty("user");
        String pw = config.getProperty("pw");
        
        List<String> symbols = Arrays.asList(symbolList.split(","));
        
        try {
            BigDAO db = new BigDAO(dbname, user, pw);
            
            // Convert the list of DifferenceDTOs into a list of string lists
            //
            
            List<DifferenceDTO> diffs = db.getSymbolDifferences(startDate, endDate, symbols);
            List< List<String> > results = new ArrayList< List<String> >();
            
            // Create the header
            List<String> header = new ArrayList<String>();
            header.add("Stock symbol");
            Set<String> dates = new HashSet<String>();
            Map<String, Map<String,Double> > symbolmap = new HashMap<String, Map<String,Double> >();
            for (DifferenceDTO diff : diffs) {
                dates.add(diff.getDate());
                
                // If symbol does not yet exist in the map, create a new one
                Map<String,Double> element;
                if ((element = symbolmap.get(diff.getSymbol())) == null) {
                    element = new HashMap<String,Double>();
                    symbolmap.put(diff.getSymbol(), element);
                }
                
                // Add a new element
                element.put(diff.getDate(), diff.getDifference());
            }
            
            String[] datelist = dates.toArray(new String[0]);
            Arrays.sort(datelist);
            for (int i = 0; i < datelist.length; i++) {
                header.add(datelist[i]);
            }
            
            // Header done, now add the subsequent entries
            results.add(header);
            String[] symlist = symbolmap.keySet().toArray(new String[0]);
            Arrays.sort(symlist);
            for (String sym : symlist) {
                List<String> record = new ArrayList<String>();
                record.add(sym);  // Symbol is the first value
                
                Map<String,Double> field = symbolmap.get(sym);
                for (int j = 1; j < header.size(); j++) {
                    String date = header.get(j);
                    //String testfield = field.get(date).toString();
                    String testfield = String.format("%.4f", field.get(date));
                    record.add(testfield);
                }
                
                results.add(record);
            }
            
            CSVPrinter.FilePrinter(results, new File(filename));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
